<template>
  <div class="box">
    <el-form ref="ruleFormRef" :rules="rules" :model="form" label-position="top" :inline="true">
      <el-form-item class="project-name" label="项目名称：" label-width="80" required prop="projectId">
        <!-- <el-select :disabled="title=='计划变更详情'||title=='计划变更审批'" @change="changeProject" v-model="form.projectId" placeholder="请选择">
          <el-option
            v-for="item in store.state.projectCenter.projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          />
        </el-select> -->
        <el-input
          v-if="title == '计划变更详情' || title == '计划变更审批'"
          disabled
          v-model="form.projectName"
        />
        <SelectOption
          v-else
          :filterable="true"
          v-model="form.projectId"
          :disabled="title == '计划变更详情' || title == '计划变更审批'"
          :options="store.state.projectCenter.projectList"
          @changeValue="changeProject"
        ></SelectOption>
      </el-form-item>
      <el-form-item class="project-name" label="合同名称：" label-width="80" required prop="contractNumber">
        <!-- <el-select :disabled="title=='计划变更详情'||title=='计划变更审批'" v-model="form.contractNumber" @change="contractChange" placeholder="请选择">
          <el-option
            v-for="item in contractList"
            :key="item.id"
            :label="item.contractName"
            :value="item.id"
          />
        </el-select> -->
        <el-input
          v-if="title == '计划变更详情' || title == '计划变更审批'"
          disabled
          v-model="form.contractName"
        />
        <SelectOption
          v-else
          :filterable="true"
          v-model="form.contractNumber"
          no-data-text="该项目无关联合同"
          :disabled="title == '计划变更详情' || title == '计划变更审批'"
          :options="contractList"
          @changeValue="changeContract"
        ></SelectOption>
      </el-form-item>
      <el-form-item class="textarea" label="变更事由" required prop="applyReason">
        <el-input
          :disabled="title == '计划变更详情' || title == '计划变更审批'"
          type="textarea"
          maxlength="512"
          show-word-limit
          :rows="3"
          v-model="form.applyReason"
        />
      </el-form-item>
      <div class="history-box" v-if="form.history.length != 0">
        <p class="title">历史计划</p>
        <hr />
        <div class="historyItem" v-for="(item, index) in (form.history as any)" :key="index">
          <div class="history">
            <el-form-item class="side" label="进度节点名称">
              <el-input v-model="item.nodeName" disabled />
            </el-form-item>
            <el-form-item class="content" label="计划内容">
              <el-input v-model="item.planContent" type="textarea" :rows="3" disabled />
            </el-form-item>
            <el-form-item class="side" label="计划周期">
              <el-date-picker
                v-model="item.planPeriod"
                type="daterange"
                range-separator="至"
                format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                disabled
              />
            </el-form-item>
            <el-form-item class="content" label="考核目标">
              <el-input v-model="item.assessmentTarget" type="textarea" :rows="3" disabled />
            </el-form-item>
          </div>
          <div class="oprate"></div>
        </div>
      </div>
      <div class="history-box">
        <p class="title">变更计划</p>
        <hr />
        <div class="historyItem" v-for="(item, index) in form.current" :key="index">
          <div class="history">
            <el-form-item class="side" required label="进度节点名称">
              <el-input
                maxlength="32"
                show-word-limit
                :disabled="title == '计划变更详情' || title == '计划变更审批'"
                v-model="item.nodeName"
              />
            </el-form-item>
            <el-form-item class="content" required label="计划内容">
              <el-input
                maxlength="512"
                show-word-limit
                :disabled="title == '计划变更详情' || title == '计划变更审批'"
                v-model="item.planContent"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <el-form-item class="side" required label="计划周期">
              <el-date-picker
                :disabled="title == '计划变更详情' || title == '计划变更审批'"
                v-model="item.planPeriod"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item class="content" required label="考核目标">
              <el-input
                maxlength="512"
                show-word-limit
                :disabled="title == '计划变更详情' || title == '计划变更审批'"
                v-model="item.assessmentTarget"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
          </div>
          <div class="oprate" v-if="title == '计划变更编辑' || title == '计划变更申请'">
            <p @click="add(index)">添加</p>
            <p @click="del(index)">删除</p>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script lang="ts">
import SelectOption from '@/views/project/components/selectOption/index.vue'
import { ElMessage } from 'element-plus'
import { defineComponent, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { getContractHistory, getContractList } from '../../../api/commom'
export default defineComponent({
  props: {
    title: {
      type: String,
      default: '',
    },
  },
  components: {
    SelectOption,
  },
  setup(props) {
    let flag
    const store = useStore()
    let orgList = JSON.parse(JSON.stringify(store.state.projectCenter.orgList))
    const contractList = ref([] as any)

    const form = store.state.projectCenter.planChangesForm
    const rules = reactive({
      projectId: { required: true, message: '请选择项目' },
      contractNumber: { required: true, message: '请选择合同' },
      applyReason: { required: true, message: '请填写变更事由' },
    })
    form.current.forEach((item) => {
      item.planPeriod = [item.planStartPeriod?.slice(0, 10), item.planEndPeriod?.slice(0, 10)]
    })
    form.history.forEach((item) => {
      item.planPeriod = [item.planStartPeriod?.slice(0, 10), item.planEndPeriod?.slice(0, 10)]
    })
    const handleContractList = () => {
      getContractList(form.projectId).then((res) => {
        console.log(res.data.data, 'getContractList')
        contractList.value = res.data.data
        if (contractList.value.length == 0) {
          // ElMessage({
          //   message: '该项目暂无关联合同',
          //   type: 'warning',
          // })
        }
      })
    }
    if (props.title != '计划变更申请') {
      console.log(props.title, 'props.title')
      handleContractList()
    }
    const changeProject = (projectInfo) => {
      console.log(projectInfo, 'changeProject')
      form.contractNumber = ''
      form.history = []
      form.projectName = projectInfo.projectName
      form.projectId = projectInfo.id
    }
    const changeContract = (contractInfo) => {
      console.log(contractInfo, 'changeContract')
      form.history = []
      form.contractNumber = contractInfo.id
      form.contractName = contractInfo.contractName
      getContractHistory(contractInfo.id).then((res) => {
        console.log(res.data.data, 'getContractHistory')
        if (res.data.data.length == 0) {
          ElMessage({
            message: '该合同没有历史计划',
            type: 'warning',
          })
        } else {
          let list = res.data.data.map((item) => {
            return {
              nodeName: item.nodeName,
              // planEndPeriod: item.planEndPeriod.slice(0,10),
              // planStartPeriod: item.planStartPeriod.slice(0,10),
              // planEndPeriod: '2022-12-31T16:00:00.000+0000',
              // planStartPeriod: '2022-12-31T16:00:00.000+0000',
              planPeriod: [item.planStartPeriod?.slice(0, 10), item.planEndPeriod?.slice(0, 10)],
              planContent: item.planContent,
              assessmentTarget: item.assessmentTarget,
            }
          })
          form.history = list
          console.log(form.history, 'form.history')
        }
      })
    }
    watch(
      () => form.projectId,
      () => {
        handleContractList()
      }
    )
    const contractChange = (item) => {
      console.log(item, 'contractChange')
      getContractHistory(form.contractNumber).then((res) => {
        console.log(res.data.data, 'getContractHistory')
        if (res.data.data.length == 0) {
          ElMessage({
            message: '该合同没有历史计划',
            type: 'warning',
          })
        } else {
          let list = res.data.data.map((item) => {
            return {
              nodeName: item.nodeName,
              // planEndPeriod: item.planEndPeriod.slice(0,10),
              // planStartPeriod: item.planStartPeriod.slice(0,10),
              // planEndPeriod: '2022-12-31T16:00:00.000+0000',
              // planStartPeriod: '2022-12-31T16:00:00.000+0000',
              planPeriod: [item.planStartPeriod?.slice(0, 10), item.planEndPeriod?.slice(0, 10)],
              planContent: item.planContent,
              assessmentTarget: item.assessmentTarget,
            }
          })
          form.history = list
          console.log(form.history, 'form.history')
        }
      })
    }
    const add = (index) => {
      form.current.splice(index, 0, {
        nodeName: '',
        planPeriod: '',
        planContent: '',
        assessmentTarget: '',
      })
      console.log(form.current, 'form.current')
    }
    const del = (index) => {
      if (form.current.length == 1) {
        ElMessage({
          message: '至少保留一条变更计划',
          type: 'warning',
        })
        return
      }
      form.current.splice(index, 1)
    }
    const ruleFormRef = ref()
    const submitForm = async () => {
      return new Promise((resolve, reject) => {
        ruleFormRef.value.validate((valid) => {
          console.log(valid, 'valid')
          if (valid) {
            console.log('校验成功')
            if (form.history.length == 0) {
              ElMessage({
                message: '该合同没有历史计划',
                type: 'warning',
              })
              return
            }
            flag = true
            form.current.forEach((item) => {
              if (
                !item.nodeName ||
                !item.assessmentTarget ||
                !item.planContent ||
                !item.planPeriod
              ) {
                flag = false
              }
            })
            if (flag) {
              form.current.map((item) => {
                console.log(item.planPeriod, 'current.planPeriod')
                item.planStartPeriod = item.planPeriod[0]
                item.planEndPeriod = item.planPeriod[1]
                // delete item.planPeriod
                return item
              })
              form.history.map((item) => {
                console.log(item.planPeriod)
                item.planStartPeriod = item.planPeriod[0]
                item.planEndPeriod = item.planPeriod[1]
                // delete item.planPeriod
                return item
              })
              resolve(form)
            } else {
              ElMessage({
                message: '请输入完整的变更计划',
                type: 'warning',
              })
            }
            reject('校验失败')
          } else {
            ElMessage({
              message: '请将基本信息补充完整',
              type: 'warning',
            })
            reject('校验失败')
          }
        })
      })
    }
    return {
      form,
      store,
      rules,
      contractList,
      orgList,
      ruleFormRef,
      contractChange,
      changeProject,
      changeContract,
      add,
      del,
      submitForm,
    }
  },
  beforeUnmount() {
    console.log('beforeUnmount')
    for (let key in this.form) {
      this.form[key] = ''
    }
    this.form.history = []
    this.form.current = [
      {
        nodeName: '',
        planPeriod: '',
        planContent: '',
        assessmentTarget: '',
      },
    ]
  },
})
</script>
<style lang="scss" scoped>
.history-box {
  width: 100%;
  .title {
    font-size: 18px;
    color: #4a4aff;
  }
  .historyItem {
    display: flex;
    padding: 10px;
    margin: 10px;
    border: 1px solid rgb(205, 201, 201);
    .history {
      display: flex;
      flex-flow: row wrap;
      width: 90%;
      .side {
        width: 35%;
      }
      .content {
        width: 60%;
      }
    }
    .oprate {
      flex: 1;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      p {
        cursor: pointer;
      }
    }
  }
}
.el-form-item {
  width: 20%;
}
.project-name{
  width: 48%;
}
.textarea {
  width: 95%;
}
/deep/.el-form-item--small .el-form-item__label {
  line-height: 20px;
}
</style>
